import AsyncStorage from "@react-native-async-storage/async-storage";
import React, { useReducer, useEffect, useState } from "react";
import queryApi from "../../api/query";

const personMessageContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "message_init":
      return action.payload;
    case "editMessage":
      return action.payload;
    default:
      return state;
  }
};

export const PersonMessageProvider = ({ children }) => {
  const [personMessage, dispatch] = useReducer(dataReducer, []);
  const [isUserMessageLoading, setIsUserMessageLoading] = useState(false);
  const [isUserMessageError, setIsUserMessageError] = useState(false);

  const initMessage = (data) => {
    dispatch({ type: "message_init", payload: data });
  };

  useEffect(() => {
    const fetchData = async () => {
      setIsUserMessageLoading(true);
      setIsUserMessageError(false);
      try {
        const token = await AsyncStorage.getItem("token");
        if (!token) {
          console.log("请求userId出错");
        }
        const result = await queryApi.get("/user/usermessage", {
          headers: { Authorization: token },
        });
        initMessage(result.data.user);
      } catch (err) {
        console.log(err);
        setIsUserMessageError(true);
      }
      setIsUserMessageLoading(false);
    };
    fetchData();
  }, []);

  const editMessage = async (updateData) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      const result = await queryApi.patch("/user/usermessage", updateData, {
        headers: { Authorization: token },
      });
      dispatch({
        type: "editMessage",
        payload: result.data.newdata,
      });
    } catch (err) {
      console.log("修改用户信息出错", err);
    }
  };

  return (
    <personMessageContext.Provider
      value={{
        personMessage: personMessage,
        initMessage,
        editMessage,
        isUserMessageLoading,
        isUserMessageError,
      }}
    >
      {children}
    </personMessageContext.Provider>
  );
};

export default personMessageContext;
